package com.wondertek.poms.service.controller;

import com.alibaba.excel.EasyExcel;
import com.wondertek.poms.common.constant.Constants;
import com.wondertek.poms.common.constant.CurrentUser;
import com.wondertek.poms.common.exception.BusinessException;
import com.wondertek.poms.common.exception.MessageCodes;
import com.wondertek.poms.common.log.MethodLog;
import com.wondertek.poms.common.utils.CopyUtils;
import com.wondertek.poms.common.utils.validate.ValidateFilter;
import com.wondertek.poms.common.vo.PageBean;
import com.wondertek.poms.common.vo.ResultBean;
import com.wondertek.poms.core.service.IContentService;
import com.wondertek.poms.core.service.IPlanMovePrdInfoService;
import com.wondertek.poms.core.service.IPrdContService;
import com.wondertek.poms.core.service.IPrdInfoService;
import com.wondertek.poms.dao.po.Content;
import com.wondertek.poms.dao.po.PlanMovePrdInfo;
import com.wondertek.poms.dao.po.PrdCont;
import com.wondertek.poms.service.listener.UploadPlanMovePrdInfoListener;
import com.wondertek.poms.service.util.BeanPropertiesUtil;
import com.wondertek.poms.service.vo.PlanMovePrdInfoImportVo;
import com.wondertek.poms.service.vo.PlanMovePrdInfoVo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author evan0213
 * @description 计划移包接口
 */
@Slf4j
@RestController
@RequestMapping("plan-move-prd-info")
public class PlanMovePrdInfoController {

	@Autowired
	private IPlanMovePrdInfoService planMovePrdInfoService;
	@Autowired
	private BeanPropertiesUtil beanPropertiesUtil;
	@Autowired
	private IPrdContService prdContService;
	@Autowired
	private IContentService contentService;
	@Autowired
	private IPrdInfoService prdInfoService;

	@ApiOperation(value = "计划移包 列表", notes = "计划移包 列表")
	@GetMapping("/list")
	@MethodLog(module = "计划移包列表")
	public ResultBean list(
			PlanMovePrdInfoVo vo,
			@RequestParam(defaultValue = "1") int page,
			@RequestParam(defaultValue = "20") int rows,
			@RequestParam(defaultValue = "createTime") String sidx,
			@RequestParam(defaultValue = "desc") String sord) {

		PlanMovePrdInfo planMovePrdInfo = new PlanMovePrdInfo();
		BeanUtils.copyProperties(vo, planMovePrdInfo);
		Page<PlanMovePrdInfo> pages = planMovePrdInfoService
				.findAll(planMovePrdInfo, page, rows, sord, sidx);
		System.out.println(pages.getContent());
		return PageBean.ok(pages.getTotalPages(), pages.getTotalElements(), pages.getContent());
	}

	@ApiOperation(value = "计划移包 新增", notes = "计划移包 新增")
	@PostMapping("/add")
	@MethodLog(module = "计划移包新增", insertDB = true, opterate = 1)
	public ResultBean add(@RequestBody PlanMovePrdInfoVo vo) {
		if (vo.getPrdContId() == null && StringUtils.isBlank(vo.getContentId())) {
			return ResultBean.error("节目ID/内容ID不能都为空");
		}
		if (vo.getPrdContId() != null && StringUtils.isNotBlank(vo.getContentId())) {
			return ResultBean.error("节目ID/内容ID只能二选一");
		}
		List<String> messageList = ValidateFilter.getFilterMessage(vo, Constants.VALIDATE_DEFAULT);
		if (!messageList.isEmpty()) {
			return ResultBean.error(messageList.toString());
		}
		if (isRepeat(vo)) {
			return ResultBean.error(MessageCodes.get(MessageCodes.M980014));
		}
		if (vo.getPrdContId() != null && StringUtils.isBlank(vo.getContentId())) {
			PrdCont prdCont = prdContService.findById(vo.getPrdContId());
			if (prdCont.getPrdInfoId().equals(vo.getNewPrdInfoId())) {
				return ResultBean.error("新的商品包不能和老的商品包相同");
			}
			if (addByPrdContId(vo)) return ResultBean.ok();
		}

		if (vo.getPrdContId() == null && StringUtils.isNotBlank(vo.getContentId())) {
			if (addByContentId(vo)) return ResultBean.ok();
		}
		return ResultBean.error();
	}


	private boolean isRepeat(PlanMovePrdInfoVo planMovePrdInfoVo) {
		PlanMovePrdInfo temp = new PlanMovePrdInfo();
		CopyUtils.copyProperties(planMovePrdInfoVo, temp, "id");
		beanPropertiesUtil.setNullIfStringIsBlank(temp);
		List<PlanMovePrdInfo> list = planMovePrdInfoService.findAll(Example.of(temp));
		for (PlanMovePrdInfo info : list) {
			PlanMovePrdInfoVo vo = new PlanMovePrdInfoVo();
			PlanMovePrdInfoVo tempVo = new PlanMovePrdInfoVo();
			CopyUtils.copyProperties(info, vo, "id");
			CopyUtils.copyProperties(planMovePrdInfoVo, tempVo, "id");
			beanPropertiesUtil.setNullIfStringIsBlank(tempVo);
			beanPropertiesUtil.setNullIfStringIsBlank(vo);
			if (vo.equals(tempVo)) {
				if (planMovePrdInfoVo.getId() == null || !Objects.equals(planMovePrdInfoVo.getId(), info.getId())) {
					return true;
				}
			}
		}
		return false;
	}

	private boolean addByPrdContId(PlanMovePrdInfoVo planMovePrdInfoVo) {
		PrdCont prdCont = prdContService.get(planMovePrdInfoVo.getPrdContId());
		if (prdCont == null) {
			throw new BusinessException(MessageCodes.M980300);
		}
		PlanMovePrdInfo planMovePrdInfo = new PlanMovePrdInfo();
		BeanUtils.copyProperties(planMovePrdInfoVo, planMovePrdInfo);
		planMovePrdInfo.setOldPrdInfoId(prdCont.getPrdInfoId());
		planMovePrdInfo.setStatus("0");
		planMovePrdInfo.setCreatePerson(CurrentUser.currUserName());
		planMovePrdInfo.setCreateTime(new Date());
		planMovePrdInfoService.save(planMovePrdInfo);
		return true;
	}

	private boolean addByContentId(PlanMovePrdInfoVo planMovePrdInfoVo) {
		String contentId = planMovePrdInfoVo.getContentId();
		Content content = contentService.findByContentId(contentId);
		if (content == null) {
			throw new BusinessException(MessageCodes.M980302);
		}
		PlanMovePrdInfo planMovePrdInfo = new PlanMovePrdInfo();
		BeanUtils.copyProperties(planMovePrdInfoVo, planMovePrdInfo);
		planMovePrdInfo.setStatus("0");
		planMovePrdInfo.setCreatePerson(CurrentUser.currUserName());
		planMovePrdInfo.setCreateTime(new Date());
		planMovePrdInfoService.save(planMovePrdInfo);
		return true;
	}

	@ApiOperation(value = "计划移包 撤回", notes = "计划移包 撤回")
	@GetMapping("/withdraw")
	@MethodLog(module = "计划移包撤回", insertDB = true, opterate = 5)
	public ResultBean withdraw(String ids) {
		if (StringUtils.isBlank(ids)) {
			return ResultBean.error("撤回的计划移包id不能为空");
		}
		String[] idArr = ids.split(",");
		if (idArr.length > 0) {
			List<PlanMovePrdInfo> list = new ArrayList<>();
			for (String id : idArr) {
				PlanMovePrdInfo planMovePrdInfo = planMovePrdInfoService.findById(Long.valueOf(id));
				list.add(planMovePrdInfo);
			}
			List<String> statusList = list.stream().map(PlanMovePrdInfo::getStatus).collect(Collectors.toList());
			if (statusList.contains("1") || statusList.contains("2") || statusList.contains("3") || statusList.contains("4") || statusList.contains("5")) {
				return ResultBean.error("只能撤回待移动状态的计划");
			}
			for (String id : idArr) {
				planMovePrdInfoService.offLine(Long.valueOf(id));
			}
		}
		return ResultBean.ok();
	}

	@ApiOperation(value = "计划移包 导入", notes = "计划移包 导入")
	@PostMapping(value = "/import")
	@MethodLog(module = "计划移包撤回", insertDB = true, opterate = 6)
	public ResultBean ruleImport(MultipartFile file) {
		log.info("计划移包导入:" + file.getOriginalFilename());
		try {
			EasyExcel.read(file.getInputStream(), PlanMovePrdInfoImportVo.class, new UploadPlanMovePrdInfoListener(planMovePrdInfoService, contentService, prdContService, prdInfoService)).sheet("Sheet1").doRead();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return ResultBean.ok("导入计划移包成功");
	}

}
